﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Tin18.Library;
using Tin18.Resources;
using Tin18.Model;
using Newtonsoft.Json;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Windows.Media;
using GoogleAds;

namespace Tin18
{
    public partial class ViewPage : PhoneApplicationPage
    {
        string ID = "";
        string Cate = "";
        string Date = "";
        string Title = "";
        string Description = "";
        string Thumb = "";
        string View = "";
        public ViewPage()
        {
            InitializeComponent();
        }
        private InterstitialAd interstitialAd;
        private int CountAds = 0;
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendView("View_Page");
            if (NavigationContext.QueryString.TryGetValue("ID", out ID))
            {
                foreach (var item in App.DaLike)
                {
                    if (item.Id.Equals(ID))
                    {
                        btn_like.Tag = "like";
                        ImageBrush background = new ImageBrush();
                        background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/home_like_active.png", UriKind.Relative));
                        btn_like.Background = background;
                        break;
                    }
                }

                NavigationContext.QueryString.TryGetValue("cate", out Cate);
                Text_chuyen_muc.Text = Cate;
                NavigationContext.QueryString.TryGetValue("time", out Date);
                Text_time.Text = Date;
                NavigationContext.QueryString.TryGetValue("title", out Title);
                NavigationContext.QueryString.TryGetValue("description", out Description);
                NavigationContext.QueryString.TryGetValue("thumb", out Thumb);
                NavigationContext.QueryString.TryGetValue("view", out View);
            }


            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (!settings.Contains("CountAds"))
                settings.Add("CountAds", 0);
            else
                CountAds = int.Parse(settings["CountAds"].ToString());
            if (CountAds > 10)
            {

                interstitialAd = new InterstitialAd("ca-app-pub-6244001645310392/4692680264");
                AdRequest adRequest = new AdRequest();

                interstitialAd.ReceivedAd += interstitialAd_ReceivedAd;
                interstitialAd.LoadAd(adRequest);

                settings["CountAds"] = 0;
            }
            else
            {
                CountAds++;
                settings["CountAds"] = CountAds;
            }
            settings.Save();


            base.OnNavigatedTo(e);
        }

        void interstitialAd_ReceivedAd(object sender, AdEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Ad received successfully");
            interstitialAd.ShowAd();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (Main_pivot.SelectedIndex == 1)
            {
                Main_pivot.SelectedIndex = 0;
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }

        bool isloadWEB = false;
        private void LoadData(string id)
        {
            Layout_loading.Visibility = System.Windows.Visibility.Visible;
            string Param = MyLibrary.RanDomBase64() + MyLibrary.Base64(string.Format(AppResources.GetNewsDetail, id));
            string URL = AppResources.Server + Param;
            WebClient webclient = new WebClient();
            webclient.DownloadStringCompleted += (ss, ee) =>
                {
                    try
                    {
                    string json = ee.Result;
                
                        NewsDetailObject _Object = JsonConvert.DeserializeObject<NewsDetailObject>(json);
                        string header = "<!DOCTYPE html>" +
                                        "<html lang=\"en-US\" class=\"chrome\">" +
                                         "<head>" +
                                          "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
                                         "<meta charset=\"UTF-8\">" +
                                          "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=4\">" +
                                         "</head>" +

                                        " <body style=\"background-color: white; font-size: 18px;\">" +
                                        "<div style=\"text-align: center;\"><span style=\"font-weight: bold; color: red;\">" + Title +
                                        "</span></div><div style=\" font-style: italic;\">" + Description +
                                        "</div></br>" +
                                        "<img align=\"middle\" src=\"" + Thumb + "\" alt=\"Smiley face\" style=\" width:100%; height:auto;\"></br>";
                        string footer = "</body></html>";
                        MyWeb.NavigateToString(header + _Object.Content + footer);
                        isloadWEB = true;
                        Layout_loading.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    catch
                    {
                        Layout_loading.Visibility = System.Windows.Visibility.Collapsed;
                        Layout_network_error.Visibility = System.Windows.Visibility.Visible;
                    }
                
                };

            webclient.DownloadStringAsync(new Uri(URL));
        }

        private void MyWeb_ScriptNotify(object sender, NotifyEventArgs e)
        {
            string[] valuePair = e.Value.Split('=');
            if (valuePair != null && valuePair[0] == "rendered_height")
                MyWeb.Height = double.Parse(valuePair[1]);
        }

        private void binhluan_click(object sender, RoutedEventArgs e)
        {
            RegisterUser();
            Main_pivot.SelectedIndex = 1;
        }
        public void RegisterUser()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            if (!settings.Contains("UserID"))
            {
                byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
                string deviceID = MyLibrary.GetMD5(Convert.ToBase64String(id));
                string Version = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value.Substring(0, 5);
                // string temp = System.Environment.OSVersion.Version.Major + "." + System.Environment.OSVersion.Version.Minor;
                //  string Osvertion = temp.Substring(0, 3);
                string Osversion = "17";
                string Param = MyLibrary.RanDomBase64() + MyLibrary.Base64(string.Format(AppResources.RegisterUser, deviceID, Version, Osversion));
                string URL = AppResources.Server + Param;
                WebClient webclient = new WebClient();
                webclient.DownloadStringCompleted += (s, e) =>
                {
                    try
                    {
                        string json = e.Result;
                        if (!string.IsNullOrEmpty(json))
                        {
                            RootUserObject _Object = JsonConvert.DeserializeObject<RootUserObject>(json);
                            App.UserID = _Object.Id;
                            settings.Add("UserID", _Object.Id);
                            settings.Save();
                        }

                    }
                    catch
                    {
          
                    }
                };
                webclient.DownloadStringAsync(new Uri(URL));
            }
            else
            {
                App.UserID = settings["UserID"].ToString();

            }

        }


        private void TextBox_comment_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void TextBox_comment_LostFocus(object sender, RoutedEventArgs e)
        {

        }

        private void TextBox_comment_TextChanged(object sender, TextChangedEventArgs e)
        {
            stringCount.Text = TextBox_comment.Text.Length.ToString() + "/150";
        }

        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(App.UserID))
            {
                MessageBox.Show("Rất tiếc, không thể bình luận ngay lúc này, vui lòng thử lại sau!");
            }
            else
            {
               string noidung = TextBox_comment.Text;
               if (string.IsNullOrEmpty(noidung))
               {
                   MessageBox.Show("Bạn phải nhập nội dung trước khi gửi bình luận!");
               }
               else
               {
                   noidung = HttpUtility.UrlEncode(noidung);
                   string Param = MyLibrary.RanDomBase64() + MyLibrary.Base64(string.Format(AppResources.PostComment, ID, "0","User"+App.UserID,"",noidung));
                   string URL = AppResources.Server + Param;
                   WebClient webclient = new WebClient();
                   webclient.DownloadStringCompleted += (ss, ee) =>
                   {
                       try
                       {
                           string json = ee.Result;
                           if (!string.IsNullOrEmpty(json))
                           {
                               RootComentObject _Object = JsonConvert.DeserializeObject<RootComentObject>(json);
                               if (_Object.status.Equals("Success"))
                                   TextBox_comment.Text = "";
                               listcomment = new ListComment(ID);
                               Layout_icon.DataContext = listcomment;
                               List_Comment.DataContext = listcomment;
                           }

                       }
                       catch
                       {
                       }
                   };
                   webclient.DownloadStringAsync(new Uri(URL));
               }
            }
        }



        ListComment listcomment;
        private void Main_pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (Main_pivot.SelectedIndex)
            {
                case 0:
                    {
                      
                        if(!isloadWEB)
                        LoadData(ID);
                    }break;
                case 1:
                    {
                      
                        listcomment = new ListComment(ID);
                        Layout_icon.DataContext = listcomment;
                        List_Comment.DataContext = listcomment;
                    }break;
                default: break;
            }
        }

        private void Reload_Click(object sender, RoutedEventArgs e)
        {
            listcomment = new ListComment(ID);
            Layout_icon.DataContext = listcomment;
            List_Comment.DataContext = listcomment;
        }

        private void btn_like_Click(object sender, RoutedEventArgs e)
        {
            if (btn_like.Tag.ToString().Equals("unlike"))
            {
                DataLike data = new DataLike()
                {
                    Id = ID,
                    Thumbnail = Thumb,
                    Title = Title,
                    View = View + "+",
                    ShortDescription = Description,
                    Date = Date,
                    CategoryName = Cate
                };
                App.AddLike(data);
                btn_like.Tag = "like";
                ImageBrush background = new ImageBrush();
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/home_like_active.png", UriKind.Relative));
                btn_like.Background = background;
            }
            else
            {
                App.DeleteLike(ID);
                btn_like.Tag = "unlike";
                ImageBrush background = new ImageBrush();
                background.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/home_like_defaut.png", UriKind.Relative));
                btn_like.Background = background;
            }
        }

        private void Reload_Content_Click(object sender, RoutedEventArgs e)
        {
            LoadData(ID);
            Layout_network_error.Visibility = System.Windows.Visibility.Collapsed;
        }

      

    }

    public class RootComentObject
    {
        public string status { get; set; }
    }
}